# -*- coding: utf-8 -*-

from trac.core import *
from trac.admin import IAdminPanelProvider
from trac.web.chrome import ITemplateProvider
from trac.util.translation import _
import re
import pkg_resources

from trac.web.chrome import add_notice, add_warning, Chrome, \
                            ITemplateProvider
from trac.resource import ResourceNotFound
                 
#from model import *

from trac.ticket.model import Ticket
from trac.util.datefmt import format_date, to_datetime
                            
class AdminPanel(Component):
    implements(IAdminPanelProvider, ITemplateProvider)

    # ITemplateProvider methods

    def get_htdocs_dirs(self):
        return []

    def get_templates_dirs(self):
        return [pkg_resources.resource_filename(__name__, 'templates')]
    # IAdminPanelProvider methods

    def get_admin_panels(self, req):
        if 'TICKET_ADMIN' in req.perm:
            yield ('MailHandling', 'Mail Handling', 'mailfilter', 'Mail Filter')

    def render_admin_panel(self, req, cat, page, querychart):
        req.perm.require('TICKET_ADMIN')
        # Detail view?
        data = {}
        if req.method == 'POST':
            self._update_config(req)
            
        section = self.config['mailfilter']
        
        ret_val = ''
        for (name, value) in section.options():
            ret_val += name + '=' + value + '\n'
            
        data['mailfilter'] = ret_val

        return 'mailfilter_admin.html', data

    def _update_config(self, req):
        # get mailfilter section
        section = self.config['mailfilter']
        
        # delete old data
        for (name, value) in section.options():
            self.config.remove('mailfilter', name)
        
        # parse input data
        input_string = req.args['mailfilter']
        
        config_list = input_string.split('\n')
        for config_string in config_list:
            if config_string.find('=') == -1:
                continue
            (name, value) = config_string.split('=', 1)
            # set to memory
            section.set(name.strip(), value.strip())
            
        # save to file
        self.config.save()